import React, { useEffect, useState } from 'react';
import { Card, Row, Col, Statistic, Button, Space, Alert, Typography, Spin, List, Tag, Progress } from 'antd';
import { 
  ProjectOutlined, 
  CheckCircleOutlined, 
  ExclamationCircleOutlined,
  ClockCircleOutlined,
  CodeOutlined,
  BugOutlined,
  SettingOutlined,
  DatabaseOutlined,
  RightOutlined,
  ReloadOutlined,
  PlusOutlined,
  // EditOutlined  // 暂时屏蔽在线SQL分析功能
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { 
  healthCheck,
  getDashboardStatistics,
  DashboardStatistics,
  RecentTask
} from '../../services/api';
import './Dashboard.css';

const { Title, Text } = Typography;

interface HealthStatus {
  status: string;
  timestamp: string;
  service: string;
  version: string;
}

const Dashboard: React.FC = () => {
  const [healthStatus, setHealthStatus] = useState<HealthStatus | null>(null);
  const [dashboardData, setDashboardData] = useState<DashboardStatistics | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const navigate = useNavigate();

  useEffect(() => {
    loadDashboardData();
  }, []);

  const loadDashboardData = async () => {
    try {
      setLoading(true);
      
      // 并行加载健康检查和统计数据
      const [healthResponse, statsResponse] = await Promise.all([
        healthCheck().catch(() => null),
        getDashboardStatistics().catch(() => null)
      ]);

      if (healthResponse) {
        setHealthStatus(healthResponse.data);
      }
      
      if (statsResponse) {
        setDashboardData(statsResponse.data);
      }
      
      setError(null);
    } catch (err) {
      console.error('加载仪表盘数据失败:', err);
      setError('无法加载仪表盘数据');
    } finally {
      setLoading(false);
    }
  };

  const getTaskStatusColor = (status: string): string => {
    switch (status) {
      case 'SUCCESS': return '#52c41a';
      case 'RUNNING': 
      case 'PENDING': return '#faad14';
      case 'FAILED': return '#ff4d4f';
      default: return '#666';
    }
  };

  const getTaskStatusText = (status: string): string => {
    switch (status) {
      case 'SUCCESS': return '已完成';
      case 'RUNNING': return '运行中';
      case 'PENDING': return '等待中';
      case 'FAILED': return '失败';
      default: return status;
    }
  };

  const renderHealthAlert = () => {
    if (error) {
      return (
        <Alert
          message="服务连接失败"
          description={error}
          type="error"
          showIcon
          style={{ marginBottom: 24 }}
          action={
            <Button size="small" onClick={loadDashboardData}>
              重试
            </Button>
          }
        />
      );
    }

    if (healthStatus) {
      return (
        <Alert
          message="服务运行正常"
          description={`服务版本: ${healthStatus.version} | 最后检查: ${healthStatus.timestamp}`}
          type="success"
          showIcon
          style={{ marginBottom: 24 }}
        />
      );
    }

    return null;
  };

  const renderCoreStatistics = () => {
    if (!dashboardData) {
      return (
        <Row gutter={[16, 16]}>
          {[1, 2, 3, 4].map(key => (
            <Col xs={24} sm={12} md={6} key={key}>
              <Card>
                <Spin />
              </Card>
            </Col>
          ))}
        </Row>
      );
    }

    const { taskStatistics, sqlStatementStatistics, issueStatistics, ruleStatistics } = dashboardData;

    return (
      <Row gutter={[16, 16]}>
        <Col xs={24} sm={12} md={6}>
          <Card hoverable>
            <Statistic
              title="扫描任务"
              value={taskStatistics.totalTasks}
              prefix={<ProjectOutlined />}
              valueStyle={{ color: '#1890ff' }}
              suffix={
                <div style={{ fontSize: '12px', color: '#666', marginTop: '8px' }}>
                  <div>已完成: {taskStatistics.completedTasks}</div>
                  <div>进行中: {taskStatistics.runningTasks}</div>
                </div>
              }
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card hoverable>
            <Statistic
              title="SQL语句"
              value={sqlStatementStatistics.totalStatements}
              prefix={<CodeOutlined />}
              valueStyle={{ color: '#52c41a' }}
              suffix={
                <div style={{ fontSize: '12px', color: '#666', marginTop: '8px' }}>
                  <div>查询: {sqlStatementStatistics.queryStatements}</div>
                  <div>DDL: {sqlStatementStatistics.ddlStatements}</div>
                </div>
              }
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card hoverable>
            <Statistic
              title="兼容性问题"
              value={issueStatistics.totalIssues}
              prefix={<BugOutlined />}
              valueStyle={{ color: '#ff4d4f' }}
              suffix={
                <div style={{ fontSize: '12px', color: '#666', marginTop: '8px' }}>
                  <div>高危: {issueStatistics.highSeverityIssues}</div>
                  <div>中等: {issueStatistics.mediumSeverityIssues}</div>
                </div>
              }
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card hoverable>
            <Statistic
              title="检查规则"
              value={ruleStatistics.activeRules}
              prefix={<SettingOutlined />}
              valueStyle={{ color: '#722ed1' }}
              suffix={
                <div style={{ fontSize: '12px', color: '#666', marginTop: '8px' }}>
                  <div>总数: {ruleStatistics.totalRules}</div>
                  <div>激活: {ruleStatistics.activeRules}</div>
                </div>
              }
            />
          </Card>
        </Col>
      </Row>
    );
  };

  if (loading && !dashboardData) {
    return (
      <div className="dashboard">
        <div style={{ textAlign: 'center', padding: '50px' }}>
          <Spin size="large" />
          <div style={{ marginTop: '16px' }}>加载仪表盘数据...</div>
        </div>
      </div>
    );
  }

  return (
    <div className="dashboard">
      <div className="dashboard-header">
        <Title level={2}>
          SQL兼容性检查工具平台
          <Button 
            type="text" 
            icon={<ReloadOutlined />} 
            onClick={loadDashboardData}
            style={{ marginLeft: '16px' }}
          >
            刷新
          </Button>
        </Title>
        <Text type="secondary">快速检测MySQL/Oracle到GoldenDB的兼容性问题</Text>
      </div>

      {renderHealthAlert()}

      {/* 核心统计卡片 */}
      <div style={{ marginBottom: '24px' }}>
        <Title level={4}>数据概览</Title>
        {renderCoreStatistics()}
      </div>

      {/* 系统状态信息 - 移到顶部 */}
      <div style={{ marginBottom: '24px' }}>
        <Card title={<><DatabaseOutlined /> 系统状态</>} bordered={false}>
          {dashboardData?.systemStatus ? (
            <Row gutter={[24, 16]}>
              <Col xs={24} sm={12} md={6}>
                <div>
                  <Text strong>服务状态: </Text>
                  <Tag color={dashboardData.systemStatus.healthCheckStatus ? 'green' : 'red'}>
                    {dashboardData.systemStatus.serviceStatus}
                  </Tag>
                </div>
              </Col>
              <Col xs={24} sm={12} md={6}>
                <div>
                  <Text strong>服务版本: </Text>
                  <Text code>{dashboardData.systemStatus.serviceVersion}</Text>
                </div>
              </Col>
              <Col xs={24} sm={12} md={6}>
                <div>
                  <Text strong>数据库状态: </Text>
                  <Tag color="green">{dashboardData.systemStatus.databaseStatus}</Tag>
                </div>
              </Col>
              <Col xs={24} sm={12} md={6}>
                <div>
                  <Text strong>最后更新: </Text>
                  <Text type="secondary">{dashboardData.systemStatus.lastUpdateTime}</Text>
                </div>
              </Col>
            </Row>
          ) : (
            <Spin />
          )}
        </Card>
      </div>

      {/* 功能入口和最近任务面板 - 调整布局 */}
      <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
        {/* 压缩快捷入口宽度 */}
        <Col xs={24} md={8}>
          <Card title={<><PlusOutlined /> 分析功能</>} bordered={false}>
            <Space direction="vertical" size="middle" style={{ width: '100%' }}>
              <Button 
                type="primary" 
                block 
                size="large"
                icon={<PlusOutlined />}
                onClick={() => navigate('/create-task')}
              >
                创建新的扫描任务
              </Button>
              <Row gutter={[8, 8]}>
                {/* 暂时屏蔽在线SQL分析功能 */}
                {/* <Col span={24}>
                  <Button 
                    block 
                    icon={<EditOutlined />}
                    onClick={() => navigate('/manual-sql-analysis')}
                  >
                    在线SQL分析
                  </Button>
                </Col> */}
              </Row>
              <Button 
                block 
                icon={<SettingOutlined />}
                onClick={() => navigate('/rules')}
              >
                兼容性规则管理
              </Button>
            </Space>
          </Card>
        </Col>
        
        {/* 最近任务 - 给更多展示空间 */}
        <Col xs={24} md={16}>
          <Card 
            title={
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span><ClockCircleOutlined /> 最近任务</span>
                <Button 
                  type="link" 
                  icon={<RightOutlined />}
                  onClick={() => navigate('/tasks')}
                >
                  查看全部
                </Button>
              </div>
            } 
            bordered={false}
          >
            {dashboardData?.recentTasks ? (
              dashboardData.recentTasks.length > 0 ? (
                <List
                  itemLayout="horizontal"
                  dataSource={dashboardData.recentTasks}
                  renderItem={(task: RecentTask) => (
                    <List.Item
                      actions={[
                        <Button
                          type="link"
                          size="small"
                          onClick={() => navigate(`/tasks/${task.id}`)}
                        >
                          查看详情
                        </Button>
                      ]}
                    >
                      <List.Item.Meta
                        avatar={
                          <div style={{ 
                            width: '40px', 
                            height: '40px', 
                            borderRadius: '50%', 
                            backgroundColor: getTaskStatusColor(task.status),
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            color: 'white'
                          }}>
                            {task.status === 'SUCCESS' && <CheckCircleOutlined />}
                            {(task.status === 'RUNNING' || task.status === 'PENDING') && <ClockCircleOutlined />}
                            {task.status === 'FAILED' && <ExclamationCircleOutlined />}
                          </div>
                        }
                        title={
                          <div>
                            <Text strong>{task.taskName}</Text>
                            <Tag 
                              color={getTaskStatusColor(task.status)} 
                              style={{ marginLeft: '8px' }}
                            >
                              {getTaskStatusText(task.status)}
                            </Tag>
                          </div>
                        }
                        description={
                          <div>
                            <div style={{ marginBottom: '4px' }}>
                              <Text type="secondary">类型: {task.taskType}</Text>
                              {task.status === 'RUNNING' && (
                                <div style={{ marginTop: '4px' }}>
                                  <Progress percent={task.progress} size="small" />
                                </div>
                              )}
                            </div>
                            <div>
                              <Text type="secondary" style={{ fontSize: '12px' }}>
                                SQL语句: {task.sqlStatementCount} | 问题: {task.issueCount} | 
                                更新时间: {task.updatedAt}
                              </Text>
                            </div>
                          </div>
                        }
                      />
                    </List.Item>
                  )}
                />
              ) : (
                <div style={{ textAlign: 'center', padding: '40px' }}>
                  <Text type="secondary">暂无任务记录</Text>
                  <br />
                  <Button 
                    type="primary" 
                    style={{ marginTop: '16px' }}
                    onClick={() => navigate('/create-task')}
                  >
                    创建第一个任务
                  </Button>
                </div>
              )
            ) : (
              <Spin />
            )}
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Dashboard;